package cn.xiaopengstack.trigger.listener;

/**
 * @author jiangyangang
 */

import cn.xiaopengstack.domain.activity.model.entity.ActivitySkuRechargeEntity;
import cn.xiaopengstack.domain.activity.model.entity.SkuRechargeUnpaidOrderEntity;
import cn.xiaopengstack.domain.activity.service.IRaffleActivityQuotaService;
import cn.xiaopengstack.domain.credit.model.entity.TradeCreditEntity;
import cn.xiaopengstack.domain.credit.service.ICreditAdjustService;
import cn.xiaopengstack.domain.rebate.event.SendBehaviorRebateEvent;
import cn.xiaopengstack.domain.rebate.model.valobj.RebateTypeVO;
import cn.xiaopengstack.domain.strategy.model.entity.UserEntity;
import cn.xiaopengstack.domain.xxx.model.valobj.TradeNameVO;
import cn.xiaopengstack.domain.xxx.model.valobj.TradeTypeVO;
import cn.xiaopengstack.types.enums.ResponseCode;
import cn.xiaopengstack.types.event.BaseEvent;
import cn.xiaopengstack.types.exception.AppException;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.annotation.SelectorType;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.math.BigDecimal;

/**
 * @author jiangyangang
 */
@RocketMQMessageListener(
        topic = "send_rebate_topic",
        consumerGroup = "jyg-big-marketing-group",
        selectorType = SelectorType.TAG,
        selectorExpression = "*"
)
@Component
@Slf4j
public class BehaviorRebateCustomer implements RocketMQListener<String> {

    @Resource
    private IRaffleActivityQuotaService raffleActivityQuotaService;

    @Resource
    private ICreditAdjustService creditAdjustService;

    @Override
    public void onMessage(String message) {

        try {
            BaseEvent.EventMessage<SendBehaviorRebateEvent.SendBehaviorRebateMessage> baseRebateMessage = JSONObject.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendBehaviorRebateEvent.SendBehaviorRebateMessage>>() {
            }.getType());

            SendBehaviorRebateEvent.SendBehaviorRebateMessage rebateMessage = baseRebateMessage.getMessage();
            RebateTypeVO rebateTypeVO = RebateTypeVO.valueOf(rebateMessage.getRebateType());

            switch (rebateTypeVO) {
                case SKU:
                    // 保存
                    ActivitySkuRechargeEntity activitySkuRechargeEntity = ActivitySkuRechargeEntity.builder()
                            .outBusinessNo(rebateMessage.getBizId())
                            .user(UserEntity.builder().userId(rebateMessage.getUserId()).build())
                            .sku(Long.valueOf(rebateMessage.getRebateConfig()))
                            .rechargeTime(rebateMessage.getBehaviorTime())
                            .build();
                    SkuRechargeUnpaidOrderEntity order = raffleActivityQuotaService.createOrder(activitySkuRechargeEntity);
                    log.info("行为返利充值成功 topic: {} message: {} order: {}", "send_rebate_topic", message, order.getOrderId());
                    break;
                case INTEGRAL:
                    // 积分返现（增加抽奖次数），扣减额度
                    TradeCreditEntity tradeCreditEntity = TradeCreditEntity.builder()
                            .tradeType(TradeTypeVO.FORWARD)
                            .userId(rebateMessage.getUserId())
                            .tradeName(TradeNameVO.REBATE)
                            .amount(new BigDecimal(rebateMessage.getRebateConfig()))
                            .outBusinessNo(rebateMessage.getBizId())
                            .build();
                    String creditOrder = creditAdjustService.createOrder(tradeCreditEntity);
                    log.info("行为积分返利充值成功 topic: {} message: {} order: {}", "send_rebate_topic", message, creditOrder);
                    break;
                default:
                    log.info("监听用户行为返利消息 - 未知的返利活动 topic: {} message: {}", "send_rebate_topic", rebateMessage);
                    break;
            }

        } catch (AppException e) {
            if (ResponseCode.INDEX_DUP.getCode().equals(e.getCode())) {
                log.warn("监听用户行为返利消息，消费重复 topic: {} message: {}", "send_rebate_topic", message, e);
                return;
            }
            throw e;
        } catch (Exception e) {
            log.error("监听用户行为返利消息，消费失败 topic: {} message: {}", "send_rebate_topic", message, e);
            throw e;

        }
    }

    public static void main(String[] args) {
        String message = "{\"id\":\"72931108289\",\"key\":\"xiaofuge_sku_20250721\",\"message\":{\"behaviorTime\":1753086262000,\"bizId\":\"xiaofuge_sku_20250721\",\"rebateConfig\":\"9011\",\"rebateDesc\":\"签到返利-sku额度\",\"rebateType\":\"sku\",\"userId\":\"xiaofuge\"},\"sendDate\":1753089016219}";

        BaseEvent.EventMessage<SendBehaviorRebateEvent.SendBehaviorRebateMessage> rebateMessage = JSONObject.parseObject(message, new TypeReference<BaseEvent.EventMessage<SendBehaviorRebateEvent.SendBehaviorRebateMessage>>() {
        }.getType());

        System.out.println(JSONObject.toJSONString(rebateMessage.getMessage()));
    }
}
